<template>
  <view class="item_detail">
    <!-- 淘礼金模态框 -->
    <CashgiftPop :itemDetail="itemDetail" @close="closeCashgift" ref="cashgiftPop" />
    <!-- 历史价格模态框 -->
    <History v-if="showHistory" @close="closeHistory" :catchtouchmove="true" :itemDetail="itemDetail" />
    <!-- 分享模态框 -->
    <Share v-if="showShare" @close="closeShare" :catchtouchmove="true" :userInfo="userInfo" :itemDetail="itemDetail" />
    <Head title="商品详情" :scrollTop="scrollTop">
      <!-- <text slot="action">搜索</text> -->
    </Head>
    <!-- 轮播 -->
    <swiper class="swiper" :indicator-dots="true" :autoplay="true" :interval="5000" :duration="600" indicator-color="#ccc"
      indicator-active-color="#FC3F78">
      <block v-for="(item,index) in itemDetail.imgs" :key="index">
        <swiper-item v-if="item">
          <view class="swiper_image" @click="previewImg(item, itemDetail.imgs)">
            <ImageLoad :src="item" mode="widthFix"/>
          </view>
        </swiper-item>
      </block>
    </swiper>
    <!-- 优惠信息 -->
    <view class="coupon_box">
      <view class="coupon_left">
        <text class="coupon_price">￥{{itemDetail.actualPrice}}</text>
        <text class="origin_price">￥{{itemDetail.actualPrice + itemDetail.couponPrice || 0}}</text>
      </view>
      <view class="coupon_right">
        <view class="discount">
          {{itemDetail.couponPrice}}元优惠
        </view>
        <view class="out_date">
          {{itemDetail.couponEndTime.slice(0,10)}}过期
        </view>
      </view>
    </view>
    <!-- 商品表头信息 -->
    <view class="item_basic">
      <!-- #ifndef APP-PLUS -->
      <view class="btn_group" v-if="itemDetail.title">
        <!-- 分享icon -->
        <i class="iconfont icon-fenxiang" @click="showShare = true"></i>
      </view>
      <!-- #endif -->
      <view class="title">
        {{itemDetail.title || '↓↓↓↓↓↓↓↓↓↓↓↓'}}
      </view>
      <!-- 展开历史价格 -->
      <view class="history_price" v-if="isDev === 'release'">
        <button class="cu-btn bg-grey"  @click="showHistoryFun">点我查看价格走势</button>
      </view>
      <view class="desc">
        {{itemDetail.desc || '↑↑↑↑↑↑↑↑↑↑↑↑↑'}}
      </view>
      <view class="tab">
        <!-- 活动类型，1-无活动，2-淘抢购，3-聚划算 -->
        <!-- <text class="activity" v-if="itemDetail.activityType !== 1">{{itemDetail.activityType === 2 ? '淘抢购' : '聚划算'}}</text> -->
        <text class="item_brand" v-if="itemDetail.brandName">{{itemDetail.brandName}}</text>
      </view>
      <view class="month_sale" v-if="itemDetail.title">
        <text v-if="itemDetail.monthSales">月销：{{itemDetail.monthSales}}</text>
        <text>快递：免运费</text>
        <text v-if="returnGold" :style="isDev === 'release' ? 'color: red' : ''">预估返:{{returnGold}} 积分</text>
      </view>
      <view class="score_box">
        <view class="cu-capsule">
          <view class="cu-tag bg-red">
            <i class="iconfont icon-miaoshu"></i>
          </view>
          <view class="cu-tag line-red">
            描述:{{itemDetail.descScore}}
          </view>
        </view>
        <view class="cu-capsule">
          <view class="cu-tag bg-red">
            <i class="iconfont icon-aixin"></i>
          </view>
          <view class="cu-tag line-red">
            服务:{{itemDetail.serviceScore}}
          </view>
        </view>
        <view class="cu-capsule">
          <view class="cu-tag bg-red">
            <i class="iconfont icon-wuliu2"></i>
          </view>
          <view class="cu-tag line-red">
            物流:{{itemDetail.shipScore}}
          </view>
        </view>
      </view>
    </view>
    <!-- 相似推荐 -->
    <view class="would_like" v-if="likeList && likeList.length > 0">
      <h3>相似推荐</h3>
      <view class="like_box">
        <WouldLike :likeList="likeList" />
      </view>
    </view>
    <!-- 商品详情图 -->
    <view class="detail_img">
      <h3>宝贝详情</h3>
      <view class="item" v-for="(item, index) in itemDetail.detailPics || itemDetail.imgs" :key="index">
        <ImageLoad v-if="item" :src="item" mode="widthFix"/>
      </view>
    </view>
    <!-- 底部按钮组 -->
    <view class="bottom_btn" v-if="isDev === 'release' && itemDetail.title">
      <!-- 收藏 -->
      <button class="bton_group favorite_btn" @click="favorite">
        <i class="iconfont" :class="hasFavorite ? 'icon-aixin' : 'icon-aixin1'"></i>
      </button>
      <!-- 淘礼金 -->
      <button class="bton_group cashgift_btn" @click="showCashgift">
        <i class="iconfont icon-hongbao"></i>
      </button>
      <!-- 分享 -->
      <!-- <button class="bton_group share_btn" @click="showShare = true">
        <i class="iconfont icon-fenxiang"></i>
      </button> -->
      <!-- #ifdef H5 || APP-PLUS -->
      <button class="bton_group copy_tkl" @click="goWebView">去淘宝购买</button>
      <!-- #endif -->
      <!-- #ifndef H5 || APP-PLUS -->
      <button class="bton_group copy_tkl" @click="copyTkl" v-if="isDev === 'release' && userInfo.tradeParentId">复制下单返{{returnGold}}积分</button>
      <button class="bton_group copy_tkl" @click="copyTkl" v-else-if="isDev === 'release' && !userInfo.tradeParentId">绑定单号下单返{{returnGold}}积分</button>
      <button class="bton_group copy_tkl_full" @click="copyTkl" v-else>复制商品标题</button>
      <!-- #endif -->
    </view>
    <!-- 绑定单号提示悬浮窗 -->
    <view class="go_order_box" v-if="!userInfo.tradeParentId && isDev === 'release'">
      <image src="https://mtds.oss-cn-hangzhou.aliyuncs.com/taoke_rabbit/itemdetail/redPacket.png" mode="widthFix" class="red_packet" @click="goOrder"></image>
    </view>
    <!-- 检测剪贴板淘口令 -->
    <ImageModal ref="imagemodal"/>
    <ScrollToTop :scrollTop="scrollTop" />
    <!-- 消息弹框 -->
    <message ref="message"/>
  </view>
</template>

<script>
  import Head from '@/pages/pagecomponents/head'
  import WouldLike from './components/wouldlike'
  import CashgiftPop from './components/cashgift'
  import History from './components/history'
  import Share from './components/share'
  import ImageModal from '@/pages/home/components/imagemodal'
  import ScrollToTop from '@/pages/pagecomponents/other/scrolltotop'
  import ImageLoad from '@/pages/pagecomponents/other/imageload'
  export default {
    components: {
      Head,
      WouldLike,
      Share,
      CashgiftPop,
      History,
      ImageModal,
      ScrollToTop,
      ImageLoad,
    },
    data() {
      return {
        appNameCNY: this.appNameCNY, // 应用中文名
        scrollTop: 0, // 屏幕滚动高度
        id: -1, // 大淘客商品id
        goodsId: -1, // 商品id
        likeList: [],
        itemDetail: {
          itemLink: '',
          remigs: [],
          shipScore: 0,
          serviceScore: 0,
          descScore: 0,
          brandName: '',
          activityType: 1,
          couponEndTime: '',
          couponPrice: '',
          originalPrice: '',
          actualPrice: '',
          imgs: [],
          title: ''
        },
        hasFavorite: false,
        showShare: false, //显示分享模态框
        showHistory: false, // 历史价格弹出框
        showCashgiftFlag: false, // 淘礼金弹出框
      }
    },
    onShareAppMessage(res) {
      // 小程序分享
      return {
        title: `您的好友${this.userInfo.nickName || ''}为你省去了${this.itemDetail.couponPrice || 0}元`,
        desc: `${this.appNameCNY}是最好的比价平台，一定要感谢你的朋友`,
        path: `/pages/home/index?redirect=` + encodeURIComponent(`/pages/itemdetail/index?id=${this.id}&&goodsId=${this.goodsId}`),
        imageUrl: this.itemDetail.imgs[0] || ''
      }
    },
    onPullDownRefresh() {
      // 下拉刷新
      this.getItemDetail('pullDown')
      let token = uni.getStorageSync('token')
      if (token) {
        this.getFavoriteStatus()
      }
    },
    onPageScroll(e) {
      // 滚动条滚动
      this.scrollTop = e.scrollTop
    },
    computed: {
      isDev(){
        return this.$store.state.isDev
      },
      userInfo(){
        return this.$store.state.userInfo
      },
      returnGold() {
        // 计算返还积分，不算用户等级
        let commissionRate = this.itemDetail.commissionRate
        let actualPrice = this.itemDetail.actualPrice
        let originGold = actualPrice * commissionRate * 0.01 * 10 // 实际佣金转换积分
        let userGold = originGold * 0.2 // 用户等级获得积分
        if (commissionRate <= 0 || userGold <= 0) {
          return 0
        }
        if (this.userInfo.level) {
          userGold = userGold * this.userInfo.level
        }
        return Math.ceil(userGold)
      },
    },
    onShow(){
      // 注册当前页面refs到store
      this.$store.commit('resignRefs', this.$refs)
    },
    onLoad(option) {
      if(option.itemLink){ // 直接传入itemLink则只查询历史价格
        this.itemDetail.itemLink = decodeURIComponent(option.itemLink)
        uni.showToast({
          icon: 'none',
          duration: 2500,
          title: '无优惠信息，不过您仍然可以查看历史价格'
        });
        return
      }
      
      this.goodsId = option.goodsId
      this.id = option.id
      this.getItemDetail()
      let token = uni.getStorageSync('token')
      if (token) {
        this.getFavoriteStatus()
      }
    },
    methods: {
      goWebView(){
        this.$refs['message'].showLoading() // 提示加载中弹框
        this.$api.wyapi.getTkl({
          para: this.goodsId,
          deepcoupon: 1, // 默认值0，1表示对联盟产品无官方优惠券时，则进行检查是否有商家合作券
        }).then(res => {
          this.$refs['message'].hideLoading() // 隐藏加载中弹框
          plus.runtime.openURL(`taobao:${res.data.coupon_click_url.slice(6)}`)
        })
      },
      copyTkl() {
        // #ifndef H5 || APP-PLUS
        getApp().mtj.trackEvent('item_tkl', { // 埋点统计
          item_name: this.itemDetail.dtitle || this.itemDetail.title,
          user_id: this.userInfo.id || 0,
        });
        // #endif
        // 复制淘口令
        let copyText = ''
        // #ifndef H5
        if (this.isDev === 'dev') {
          copyText = `复制商品信息成功:${this.itemDetail.title}`
          uni.setClipboardData({
            data: copyText,
            success: function() {
              uni.hideToast(); // 隐藏默认提示框
              uni.showModal({
                content: copyText,
                showCancel: false
              });
            }
          });
        } else {
          this.$refs['message'].showLoading() // 提示加载中弹框
          this.$api.wyapi.getTkl({
            para: this.goodsId,
            deepcoupon: 1, // 默认值0，1表示对联盟产品无官方优惠券时，则进行检查是否有商家合作券
          }).then(res => {
            this.$refs['message'].hideLoading() // 隐藏加载中弹框
            copyText = `${this.itemDetail.title}\r\n浏览器访问：${res.data.coupon_short_url}\r\n${res.data.coupon_info ? '优惠券：【' + this.itemDetail.couponPrice + '元】\r\n': ''}券后价：【${this.itemDetail.actualPrice}元】\r\n${this.itemDetail.couponEndTime ? '优惠过期时间：【' + this.itemDetail.couponEndTime + '】\r\n': ''}淘口令:【${res.data.tbk_pwd}】\r\n下单方法：复制此条信息→打开手淘领券`
            uni.setClipboardData({
              data: copyText,
              success: function() {
                uni.hideToast(); // 隐藏默认提示框
                uni.showModal({
                  content: `复制优惠券淘口令成功:${res.data.tbk_pwd},下单方法：直接打开手淘领券下单`,
                  showCancel: false
                });
              }
            });
          })
        }
        // #endif
        // #ifdef H5
        this.$refs['message'].showLoading() // 提示加载中弹框
        this.$api.wyapi.getTkl({
          para: this.goodsId,
          deepcoupon: 1, // 默认值0，1表示对联盟产品无官方优惠券时，则进行检查是否有商家合作券
        }).then(res => {
          this.$refs['message'].hideLoading() // 隐藏加载中弹框
          copyText = `复制淘口令成功:${res.data.tbk_pwd}`
          const btn = document.querySelector('.copy_tkl');
          const input = document.createElement('input');
          input.setAttribute('readonly', 'readonly');
          input.setAttribute('value', copyText);
          document.body.appendChild(input);
          input.select();
          input.setSelectionRange(0, 9999);
          if (document.execCommand('copy')) {
            document.execCommand('copy');
            uni.showModal({
              content: copyText,
              showCancel: false
            });
          }
          document.body.removeChild(input);
        })
        // #endif
      },
      previewImg(item, imgList) {
        uni.previewImage({
          current: item, // 当前图片
          urls: imgList // 需要预览的图片数组
        })
      },
      getWouldLike() {
        // 淘宝相似推荐物料
        this.$api.user.materialList({
          pageId: 1,
          pageSize: 10,
          materialId: 13256, // 相似推荐物料
          item_id: this.goodsId,
        }).then(res => {
          this.likeList = res.data.list
        })
      },
      getItemDetail(type) {
        if(this.id === '-1' && this.goodsId === '-1'){
          // 不查询商品直接查询历史价格
          return
        }
        this.$api.dtkapi.getItemDetail({
          version: 'v1.1.0',
          goodsId: this.goodsId,
        }).then(res => {
          if(!res.data){ // 查询商品信息失败
            uni.showToast({
              icon: 'none',
              title: res.msg
            });
          }
          if (type === 'pullDown') {
            // 下拉刷新
            uni.stopPullDownRefresh();
          } else {
            // #ifndef H5 || APP-PLUS
            getApp().mtj.trackEvent('itemdetail', { // 埋点统计
              item_name: res.data.dtitle || res.data.title,
              user_id: this.userInfo.id || 0,
            });
            // #endif
          }
          res.data.reimgs = res.data.reimgs && res.data.reimgs.split(',')
          res.data.imgs = res.data.imgs && res.data.imgs.split(',')
          res.data.detailPics = res.data.detailPics && res.data.detailPics.split(',')
          this.itemDetail = res.data
          this.id = res.data.id
          this.goodsId = res.data.goodsId
          this.getWouldLike()
        })
      },
      getFavoriteStatus() {
        // 获取商品收藏状态
        this.$api.user.getFavoriteStatus({
          goodsId: this.goodsId
        }).then(res => {
          this.hasFavorite = res.data.hasFavorite
        })
      },
      showCashgift() {
        this.showCashgiftFlag = true;
        this.$refs.cashgiftPop.show();
      },
      closeCashgift() {
        this.showCashgiftFlag = false;
      },
      closeShare() {
        this.showShare = false;
      },
      showHistoryFun(){
        let token = uni.getStorageSync('token')
        if(token){
          this.showHistory = true
        }else{
          uni.showModal({
            title: '提示',
            cancelText: '不行',
            confirmText: '行',
            content: '万水千山总是情，登录后再看行不行~',
            success: res => {
              if (res.confirm) {
                uni.navigateTo({
                  url: '/pages/usercenter/login'
                });
              } else if (res.cancel) {
                this.showHistory = true
              }
            }
          });
        }
      },
      closeHistory() {
        this.showHistory = false;
      },
      goOrder(){
        uni.navigateTo({
          url: '/pagesusercenter/order/index'
        });
      },
      favorite() {
        // 收藏/取消收藏
        let itemDetail = JSON.parse(JSON.stringify(this.itemDetail))
        itemDetail.tId = itemDetail.id
        delete itemDetail.id // 删除自带id
        let favorite = !this.hasFavorite; // true收藏,false取消收藏
        this.$api.user.favoriteItem({ ...itemDetail,
          favorite: favorite,
        }).then(res => {
          let msg = ''
          if (!favorite) {
            msg = '取消'
          } else {
            // #ifndef H5 || APP-PLUS
            getApp().mtj.trackEvent('favorite', { // 埋点统计
              item_name: this.itemDetail.dtitle || this.itemDetail.title,
              user_id: this.userInfo.id || 0,
            });
            // #endif
          }
          uni.showToast({
            title: `${msg}收藏成功！`
          });
          this.hasFavorite = favorite;
          // 调用刷新用户信息方法
          this.$store.commit('refreshUserInfo')
        })
      },
    }
  }
</script>

<style scoped lang="scss">
  .item_detail {
    padding-bottom: 100upx;
    background-color: #ffffff;
    .top_btn {
      position: relative;
      .iconfont {
        position: fixed;
        z-index: 2000;
        top: var(--status-bar-height);
        /* #ifdef H5 */
        top: 20upx;
        /* #endif */
        left: 20upx;
        padding: 15upx;
        font-size: 30upx;
        color: #ffffff;
        border-radius: 50%;
        display: inline-block;
        background: rgba(0, 0, 0, 0.5);
      }
    }
    .swiper {
      width: 100%;
      height: 700upx;
      .swiper_image {
        width: 100%;
        height: 700upx;
        overflow: hidden;
      }
    }
    .coupon_box {
      position: relative;
      padding: 0 40upx;
      width: 100%;
      height: 135upx;
      background: url('https://mtds.oss-cn-hangzhou.aliyuncs.com/taoke_rabbit/itemdetail/coupon.png') no-repeat;
      background-size: 100% 100%;
      color: #ffffff;
      .coupon_left {
        line-height: 135upx;
        .coupon_price {
          font-size: 50upx;
        }
        .origin_price {
          text-decoration: line-through;
          margin-left: 20upx;
          color: #d5d1c8;
          font-size: 35upx;
        }
      }
      .coupon_right {
        text-align: center;
        position: absolute;
        right: 60upx;
        top: 20upx;
        line-height: 50upx;
      }
    }
    .item_basic {
      position: relative;
      .btn_group {
        position: absolute;
        top: 30upx;
        right: 30upx;
        .iconfont {
          font-size: 30upx;
          color: #1a1a1a;
        }
      }
      .title {
        padding: 20upx 120upx 5upx 30upx;
        color: #393939;
        font-size: 35upx;
        font-weight: 600;
        display: -webkit-box;
        -webkit-box-orient: vertical;
        -webkit-line-clamp: 2;
        overflow: hidden;
      }
      .history_price{
        padding: 0 30upx 0;
        text-align: center;
        .cu-btn{
          width: 100%;
        }
      }
      .desc {
        color: #afb2b7;
        margin: 10upx 0;
        padding: 0 30upx;
        display: -webkit-box;
        -webkit-box-orient: vertical;
        -webkit-line-clamp: 2;
        overflow: hidden;
      }
      .tab {
        padding: 10upx 30upx;
        text {
          margin-right: 10upx;
          padding: 5upx 10upx;
        }
        .activity {
          color: #f4757e;
          background-color: #feeae9;
        }
        .item_brand {
          color: #9dced7;
          background-color: #edf3f9;
        }
      }
      .month_sale {
        padding: 10upx 30upx;
        color: #c9cdd6;
        text {
          display: inline-block;
          width: 33%;
        }
      }
      .score_box {
        padding: 10upx 30upx;
        .cu-capsule {
          width: 32%;
        }
      }
    }
    .would_like {
      margin-top: 20upx;
      h3 {
        font-weight: 600;
        text-align: center;
      }
      .like_box {
        padding: 20upx 30upx 0;
      }
    }
    .detail_img {
      padding: 30upx 0 0upx;
      h3 {
        font-weight: 600;
        text-align: center;
      }
      .item {
        width: 100%;
        height: auto;
        overflow: hidden;
      }
    }
    .bottom_btn {
      position: fixed;
      bottom: 0;
      left: 0;
      right: 0;
      height: 100upx;
      .bton_group {
        height: 100upx;
        line-height: 100upx;
        border-radius: 0;
        height: 100%;
        display: inline-block;
      }
      .iconfont {
        height: 100upx;
        line-height: 100upx;
        font-size: 40upx;
        font-weight: 600;
      }
      .favorite_btn, .cashgift_btn, .share_btn {
        color: #000000;
        background-color: #ffffff;
        width: 150upx;
        .icon-fenxiang{
          font-size: 35upx;
        }
        .icon-aixin {
          color: red;
          animation: heart_red .5s cubic-bezier(.17, .89, .32, 1.49);
        }
      }
      @keyframes heart_red {
        0%, 17.5% {
          font-size: 0;
        }
      }
      .copy_tkl {
        font-size: 30upx;
        color: #ffffff;
        background-color: #294d7d;
        width: 450upx;
      }
      .copy_tkl_full{
        color: #ffffff;
        background-color: #294d7d;
        width: 750upx;
      }
    }
    .go_order_box{
      position: fixed;
      right: 10upx;
      bottom: 300upx;
      .red_packet{
        width: 100upx;
      }
    }
  }
</style>
